const MyPromise = (function() {
  const PENDING = 'pending';
  const RESOLVED = 'resolved';
  const REJECTED = 'rejected';
  function MinPromise(fn) {
    const _this = this;
    // promise的状态
    this.state = PENDING;
    // resolve的函数
    this.resolveCallBack = [];
    // reject的函数
    this.rejectedCallBack = [];

    // 保存函数resolve或者reject的值
    this.value = null;

    // promise 的resolve函数;

    function resolve(value) {
      //
      // if (_this.value instanceof MinPromise) {
      //   _this.value.then(resolve, reject);
      //   return;
      // }
      setTimeout(function() {
        // 只有在 PENDING状态才执行
        if (_this.state === PENDING) {
          // 保留promise的值
          _this.value = value;
          // 修改promise的状态;
          _this.state = RESOLVED;

          // 执行then里面的函数, 顺序执行, 然后把执行结果往下传
          _this.resolveCallBack.reduce(function(total, callBack) {
            return callBack(total);
          }, value);

          // 清楚数组对象
          _this.resolveCallBack = [];
        }
      }, 0);
    }

    function reject(value) {
      _this.value = value;
      _this.state = REJECTED;
      setTimeout(function() {
        _this.rejectedCallBack.reduce(function(total, callBack) {
          return callBack(total);
        }, value);

        _this.rejectedCallBack = [];
      }, 0);
    }

    try {
      fn(resolve, reject);
    } catch {

    }
  }

  MinPromise.prototype.then = function (resolve, rejected) {
    function fun (value) {
      return value;
    }
    const res = typeof resolve === 'function' ? resolve: fun;
    const rej = rejected;
    if (this.state === PENDING) {
      this.resolveCallBack.push(res);
    }

    if (this.state === PENDING && typeof rej === 'function') {
      this.rejectedCallBack.push(rej)
    }

    if (this.state === RESOLVED) {
      res(this.value)
    }

    if (this.state === REJECTED && typeof rej === 'function') {
      rej(this.value)
    }

    return this;
  }



  MinPromise.prototype.catch = function (rejected) {
    function fun (value) {
      return value;
    }
    const rej = typeof rejected === 'function' ? rejected: fun;

    if (this.state === PENDING) {
      this.rejectedCallBack.push(rej);
    }

    if (this.state === REJECTED) {
      rej(this.value)
    }
    return this;
  }

  return MinPromise;
})();



window.Promise = MyPromise;


function fnnn() {
  return new Promise(function(res, rej) {
    setTimeout(function() {
      rej('errewere');
    }, 2000);
  });
}

// function fn1() {
//   return new Promise(function(res, rej) {
//     setTimeout(function() {
//       res(2);
//     }, 2000);
//   });
// }

fnnn().then((res) => {
  console.log(res);
  return 'hahha'
}).then((res) => {
  console.log(res, 'res');
}).catch((err) => {
  console.log(err, 'errr');
})
